package edu.ynu.se.xiecheng.achitectureclass.common.utils;

import edu.ynu.se.xiecheng.achitectureclass.common.dto.CameraDeviceValueDTO;
import okhttp3.*;
import com.google.gson.Gson;

import java.io.IOException;

public class CameraDeviceValueUtil {

    private static final String CAPTURE_URL = "https://open.ys7.com/api/lapp/device/capture";
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/x-www-form-urlencoded");

    public static CameraDeviceValueDTO getCaptureData(String accessToken, String deviceSerial, String channelNo, String quality) throws IOException {
        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("accessToken", accessToken)
                .add("deviceSerial", deviceSerial)
                .add("channelNo", channelNo)
                .add("quality", quality)
                .build();

        Request request = new Request.Builder()
                .url(CAPTURE_URL)
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            String responseBody = response.body().string();
            Gson gson = new Gson();
            return gson.fromJson(responseBody, CameraDeviceValueDTO.class);
        }
    }

    public static void main(String[] args) {
        try {
            String accessToken = "ra.5re72ai38g4y7gky9ghls5dzb2equqku-491d6ysuja-0bzlevz-5zrd54nns";
            String deviceSerial = "AC0174303";
            String channelNo = "1";
            String quality = "3";

            CameraDeviceValueDTO cameraDeviceValueDTO = getCaptureData(accessToken, deviceSerial, channelNo, quality);
            System.out.println("Message: " + cameraDeviceValueDTO.getMsg());
            System.out.println("Code: " + cameraDeviceValueDTO.getCode());
            System.out.println("Picture URL: " + cameraDeviceValueDTO.getData().getPicUrl());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
